from database.park_location_record_table import ParkLocationRecordTable
from manager.lock_manager import LockManager
from model.park_spider import ParkSpider
from model.park_platform import ParkPlatform
from model.car_number import CarNumber
from model.result import Result
from model.error import ParkSpiderError, ParkSpiderErrorCode, TokenExpireError

from urllib import parse
import common.http as http
import spider_config
import json
import datetime
import time
from common.logger import logger


class YimaParkSpider(ParkSpider):
    def platform(self) -> ParkPlatform:
        return ParkPlatform(spider_config.yima_park_id)

    def query(self, carNumber: CarNumber) -> Result:
        account = self.getAccount()

        if not account:
            raise ParkSpiderError(ParkSpiderErrorCode.YimaAccountEmpty)

        with LockManager.instance().get(self.platform().id, account["openId"]):
            result = Result()
            result.platform = self.platform()
            result.car_number = carNumber

            url = "https://m.bolink.club/capp/api/pay/querybyplatenumber"

            headers = {
                "token": account["token"],
            }

            data = {
                "plateNumber": str(carNumber),
            }

            rsp = http.post(
                url,
                headers=headers,
                data=json.dumps(data),
                proxies=self.getProxy(),
                timeout=self.getTimeout(),
            )

            logger.debug(f"一码查询 {carNumber} 结果:{rsp.text}")

            if rsp.status_code != 200:
                result.error_code = rsp.status_code
                result.message = rsp.text
                return result

            rspJson = rsp.json()

            if rspJson["status"] == 203:
                raise TokenExpireError(account["openId"])

            time.sleep(3)

            if "msg" in rspJson and "努力查询中" in rspJson["msg"]:
                self.__recurve = True
                return self.query(carNumber)

            if rspJson["status"] != 200:
                result.success = False
                result.error_code = rspJson["status"]
                result.message = rspJson["msg"] if "msg" in rspJson else ""
                return result

            if (
                "data" not in rspJson
                or "orderList" not in rspJson["data"]
                or not rspJson["data"]["orderList"]
            ):
                result.success = False
                result.message = str(rspJson)
                return result

            info = rspJson["data"]["orderList"][0]

            # 入场时间 >= 出场时间, 判定为假数据
            if info["inTime"] >= info["outTime"]:
                result.success = False
                result.message = str(rspJson)
                return result

            result.success = True

            result.enter_time = datetime.datetime.fromtimestamp(info["inTime"])
            result.park_name = info["parkName"]
            result.price = info["money"]

            try:
                with ParkLocationRecordTable(spider_config.yima_park_id) as db:
                    record = db.query(info["parkId"], result.park_name)
                    if record:
                        result.park_name = record
                        logger.info(f"匹配到parkid:{record}")
                    else:
                        logger.info(f"未匹配到parkid:{info}")
            except Exception as e:
                logger.warning(e)

            return result
